package ar.com.vates.threads3;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;

public class Cajero implements Runnable {

	private static final int ITERATIONS = 5;
	private static final int RETIRO = 10;

	private Random rnd;

	private Cuenta cuenta;
	private String persona;

	public Cajero(Cuenta cuenta, String persona, int delay) {
		this.cuenta = cuenta;
		this.persona = persona;
		this.rnd = new Random();
	}

	@Override
	public void run() {

		for (int i = 0; i < ITERATIONS; i++) {
			this.retirarDinero();
			if (cuenta.isSobregirada())
				System.out.println(now() + " \t" + persona
						+ " la cuenta esta sobregirada");
		}
	}

	public synchronized void retirarDinero() {

		System.out.println(now() + " \t" + persona + " consulta el saldo: "
				+ cuenta.getSaldo());

		try {
			Thread.sleep(rnd.nextInt(5000) + 1);
		} catch (InterruptedException e) {
			System.out.println("Error");
		}

		if (cuenta.retirar(RETIRO))
			System.out.println(now() + " \t" + persona + " hizo retiro "
					+ RETIRO);
		else
			System.out.println(now() + " \t" + persona
					+ " no tiene saldo suficiente");
	}

	public String now() {
		String now = "";

		Calendar c = new GregorianCalendar();

		now = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":"
				+ c.get(Calendar.SECOND) + " - " + c.get(Calendar.MILLISECOND);
		return now;
	}

}